import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { Layout, Table, Input, Button, InputNumber, Popconfirm, Modal, Form, Row, Col, Select } from 'antd';

import '../style.scss';
import { validateTel, validateEmail } from '../reg'
import { actionCreators } from '../store';

const { Content } = Layout;
const { Column } = Table;

@withRouter
class subOrganization extends Component {
    state = {
        page: 10,
        searchValue: '',
        subAddVisible: false,
        resetPwdVisibale: false,
        childEditorVisible:false,
        childRecord:{},
        currentPage:1

    };
    editRef=React.createRef();
    addChildformRef=React.createRef();
    pwdRef=React.createRef();
/*     changePage = (value) => {
        this.setState({ page: value });
    }

    setSearchValue = (e) => {
        this.setState({ searchValue: e.target.value })
    }

    handleSearch = () => {
        let userName = "admin";//待修改
        this.props.searchApi(userName, this.state.searchValue)
    }

    resetSearch = () => {
        this.setState({ searchValue: '' });
        let userName = "admin";//待修改
        this.props.getConfig(userName);
    }

    deleteCon = (record) => {
        let databaseConfig = JSON.parse(record.userDatabaseConfig);
        let params = { databaseId: databaseConfig.databaseId, id: databaseConfig.id };
        this.props.deleteCon(params);
    } */
    //新增sub
    addSub = () => {
        this.setState({
            subAddVisible: true
        })
    }
    //退出sub新增
    addCancel = () => {
        this.setState({
            subAddVisible: false
        })
    }
    //保存新增的子项目
    saveAddSub = () => {
         this.addChildformRef.current.validateFields().then(values=>{
                const addValues={
                    Name:values.chargePeoName,
                    disabled:values.isEnable,
                    email:values.chargePeoEmail,
                    organizationId:this.props.parentRecord.organization,
                    password:values.pwd,
                    phone:values.subAccount,
                    superId:this.props.parentRecord.userId,
                    username:values.loginName
                }
                console.log(addValues)
                  const childUserId=this.props.parentRecord.userId;
                  this.props.addChildOrg(addValues,childUserId);
                  this.addCancel();
         })
    }
    //sub的重置密码
    resetPwd = (record) => {
        this.setState({
            resetPwdVisibale: true,
            childRecord:record
        })
    }
    //退出重置密码界面
    handleCancel = () => {
        this.setState({
            resetPwdVisibale: false
        })
    }
    //确认密码
    confirmPwd = () => {
        this.pwdRef.current.validateFields().then(values=>{
            if(values){
                const pwdValue={
                    confirmPassword:values.confirmPwd,
                    id:this.state.childRecord.userId,
                    newPassword:values.newPwd,
                    oldPassword:values.oldPwd
                };
                const childUserId=this.props.parentRecord.userId;
                this.props.childResetPwd(pwdValue,childUserId);
                this.handleCancel();
            }
       })
    }
    //删除子项目
    deleteSub = (userId) => {
        
        this.props.deleteSub(userId);

    }
    //返回上一页页面
    back=()=>{
        this.props.back();
    }
    //进入编辑
    editChild=(record)=>{
       this.setState({
        childEditorVisible:true,
        childRecord:record
       });
    }
    //退出编辑
    editorCancel=()=>{
        this.setState({
            childEditorVisible:false
        })
    }
    //保存编辑
    editorChildOrg=()=>{
        this.editRef.current.validateFields().then(value=>{
            if(value){
                const editValue={
                    Name:value.chargePeoName,
                    email:value.chargePeoEmail,
                    phone:value.chargePeoTel,
                    userId:this.state.childRecord.userId
                }
                const childUserId=this.props.parentRecord.userId;
                this.props.saveChildEdit(editValue,childUserId);
                this.editorCancel();
            }
        })
    }
    //切换enable
    toggleStatus=(record)=>{
        if(record.isEnable===0){
            //启用
            const childUserId=this.props.parentRecord.userId;
            this.props.startChildEnable(record.userId,childUserId);
        }
        else{
            //禁用
            const childUserId=this.props.parentRecord.userId;
            this.props.noChildEnable(record.userId,childUserId);
        }
       /* console.log() */
    }
    //inputNumber切换页码
    changePage=(e)=>{
        this.setState({
            currentPage:e
        })
    }
    //table切换页码
    changePageNum=(current)=>{
        this.setState({
            currentPage:current
        })
    }
    componentDidMount() {
        let userName = "admin";//待修改
        const childUserId=this.props.parentRecord.userId;
        this.props.getChildData(childUserId);
        console.log(this.props.parentRecord) 
    };

    render() {
        const { page, resetPwdVisibale, subAddVisible,childEditorVisible,childRecord ,currentPage} = this.state;
        const {childDataSource,childPageNum}=this.props;
        const {superEnable}=this.props.parentRecord;
        const pwdReg=/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,18}$/;

        const paginationProps = {
            onChange: (current) => {
              this.changePageNum(current);
            },
            current: currentPage,
            hideOnSinglePage: true,
            pageSize: 10,
            showSizeChanger: false,
          };
        const limitDecimals = (value) => {
            if (typeof value === "number") {
              return value;
            }
            if (typeof value !== "number") {
              if (value > childPageNum) {
                return value.replace(/^\d+/g, childPageNum);
              }
              return value.replace(/^(0+)|[^\d]+/g, "");
            }
          };
        return (
            <Content style={{ marginTop: 12 }}>
                <div style={{ fontWeight: 'bold' }}><span  onClick={this.back}>组织资源{">"}子项目</span>
        <Button onClick={this.addSub} style={{ float: "right" }}>新增</Button>
                </div>
                <div className="table-box" style={{ marginTop: 24 }}>
                    <Table
                        rowKey="userId"
                        pagination={paginationProps}
                        dataSource={childDataSource}>
                        
                        <Column title="序号" render={(text,render,index)=> {return (currentPage - 1) * 10 + index + 1;}}/>
                        <Column title="用户名" dataIndex="name" key="name"/>
                        <Column title="联系人姓名" dataIndex="organizationName" key="organizationName"/>
                        <Column title="联系电话" dataIndex="phone" key="phone" />
                       <Column title="状态" dataIndex="isEnable" key="isEnable" render={(text,record)=><span>{record.isEnable===0?'启用':'停用'}</span>}/>
                        <Column title="操作" dataIndex="operation" key="operation"
                            render={(text, record) => (
                                <span>
                                    {superEnable===0?( <span className="action" onClick={() => { this.toggleStatus(record) }}>{record.isEnable === 0 ? '停用' : '启用'}</span>): <span style={{color:'grey',cursor:'pointer', marginRight: '18px'}}>{record.isEnable === 0 ? '停用' : '启用'}</span>}
                                    <span className="action" onClick={()=>this.editChild(record)}>编辑</span>
                                    <span className="action" onClick={()=>this.resetPwd(record)}>重置密码</span>
                                    <span className="action" onClick={()=>this.deleteSub(record.userId)}>删除</span>
                                </span>)} />
                    </Table>
                    <div className={childPageNum > 1 ? 'footer' : 'withoutPagination'}>显示<InputNumber 
                                                             min={1}
                                                             formatter={limitDecimals}
                                                             parser={limitDecimals}
                                                             max={childPageNum}
                                                             defaultValue={1}
                                                             value={currentPage}
                                                             onChange={e=>this.changePage(e)} 
                    />项结果，共{childPageNum}项
          </div>
                </div>
                <Modal
                    destroyOnClose
                    title={<div className="titleStyle">新增子项目</div>}
                    visible={subAddVisible}
                    onCancel={this.addCancel}
                    maskClosable={false}
                    bodyStyle={{ backgroundColor: "#f0f3f6" }}
                    footer={
                        <div className="footerStyle">
                            <Button
                                type="primary"
                                htmlType="submit"
                                form="addChildForm"
                                style={{ color: "white", borderRadius: 5 }}
                            >
                                保存
              </Button>
                            <Button
                                style={{ color: "#007cdb", borderRadius: 5 }}
                                onClick={this.addCancel}
                            >
                                取消
              </Button>
                        </div>
                    }
                >
                    <Form
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 20 }}
                        ref={this.addChildformRef}
                        id="addChildForm"
                        onFinish={this.saveAddSub}
                    >
                        <Row>
                            <Col span={12}>
                                <Form.Item
                                    label={<span className="formItemStyle">隶属机构</span>}
                                    rules={[{ required: true, message: "请输入隶属机构" },]}
                                    name="subordinateOrganization"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
                                <Form.Item
                                    label={<span className="formItemStyle">子账户电话</span>}
                                    rules={[
                                        { required: true, message: "请输入子账户电话" },
                                        { validator: validateTel },
                                    ]}
                                    name="subAccount"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
                                <Form.Item
                                    label={<span className="formItemStyle">登录名</span>}
                                    rules={[{ required: true, message: "请输入登录名" },]}
                                    name="loginName"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
                                <Form.Item
                                    label={<span className="formItemStyle">是否启用</span>}
                                    initialValue={1}
                                    name="isEnable"
                                >
                                    <Select
                                        getPopupContainer={(triggerNode) => triggerNode.parentNode}
                                    >
                                        <Select.Option value={0}>启用</Select.Option>
                                        <Select.Option value={1}>停用</Select.Option>
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item
                                    label={<span className="formItemStyle">子账户姓名</span>}
                                    rules={[{ required: true, message: "请输入子账户姓名" },]}
                                    name="chargePeoName"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
                                <Form.Item
                                    label={<span className="formItemStyle">子账户邮箱</span>}
                                    rules={[{ required: true, message: "请输入子账户邮箱" }, { validator: validateEmail }]}
                                    name="chargePeoEmail"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
                                <Form.Item
                                    label={<span className="formItemStyle">密码</span>}
                                    rules={[{ required: true, message: "请输入密码" },
                                    ()=>({
                                        validator(role,value){
                                            if(value&&!value.match(pwdReg)){
                                                return Promise.reject('密码为数字字母组合')
                                            }
                                            return  Promise.resolve();
                                        }
                                    })]}
                                    name="pwd"
                                >
                                    <Input type='password' autoComplete="off" />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Form.Item
                                label={<span className="formItemStyle">备注</span>}
                                name="description"
                                style={{ width: "100%" }}
                                wrapperCol={{ span: 22 }}
                            >
                                <Input.TextArea placeholder="请输入备注" />
                            </Form.Item>
                        </Row>
                    </Form>
                </Modal>
                <Modal
                    destroyOnClose
                    title={<div className="title-Style">重置密码</div>}
                    visible={resetPwdVisibale}
                    onCancel={this.handleCancel}
                    maskClosable={false}
                    bodyStyle={{ backgroundColor: "#f0f3f6" }}
                    footer={
                        <div className="footer-Style">
                            <Button
                                type="primary"
                                style={{ color: "white", borderRadius: 5 }}
                                htmlType="submit"
                                form="pwdForm"
                            >
                                保存
                </Button>
                            <Button
                                style={{ color: "#007cdb", borderRadius: 5 }}
                                onClick={this.handleCancel}
                            >
                                取消
                </Button>
                        </div>
                    }
                >
                    <Form
                        id="pwdForm"
                        labelCol={{ span: 24 }}
                        wrapperCol={{ span: 20 }}
                        ref={this.pwdRef}
                        onFinish={this.confirmPwd}

                    >
                        <Form.Item
                            label={<span className="formItem-Style">旧密码</span>}
                            name="oldPwd"
                            rules={[
                                { required: true, message: "请输入旧密码" },
                                 ({getFieldValue})=>({
                                     validator(role,value){
                                         if(getFieldValue('newPwd')&&value.length===getFieldValue('newPwd').length&&value===getFieldValue('newPwd')){
                                             return Promise.reject('与新密码一致')
                                         }
                                         if(value&&!value.match(pwdReg)){
                                            return Promise.reject('密码为数字字母组合')
                                        }
                                         return Promise.resolve();
                                     }
                                 })
                            ]}
                        >
                            <Input type="password" autoComplete="off"/>
                        </Form.Item>
                        <Form.Item
                            label={<span className="formItem-Style">新密码</span>}
                            name="newPwd"
                            rules={[
                                { required: true, message: "请输入新密码" },
                                ({getFieldValue})=>({
                                    validator(role,value){
                                        if(value===getFieldValue('oldPwd')){
                                            return Promise.reject('与旧密码一致')
                                        }
                                        if(getFieldValue('confirmPwd')&&value.length>=getFieldValue('confirmPwd').length&&value!==getFieldValue('confirmPwd')){
                                            return Promise.reject('与确认密码不一致')
                                        }
                                        if(value&&!value.match(pwdReg)){
                                            return Promise.reject('密码为数字字母组合')
                                        }
                                     return   Promise.resolve();
                                    }
                                })
                            ]}
                        >
                            <Input type="password" autoComplete="off"/>
                        </Form.Item>
                        <Form.Item
                            label={<span className="formItem-Style">确认密码</span>}
                            name="confirmPwd"
                            rules={[
                                { required: true, message: "请输入确认密码" },
                                ({getFieldValue})=>({
                                    validator(role,value){
                                        if(value!==getFieldValue('newPwd')){
                                            return Promise.reject('两次输入不一致')
                                        }
                                        if(value&&!value.match(pwdReg)){
                                            return Promise.reject('密码为数字字母组合')
                                        }
                                        return  Promise.resolve();
                                    }
                                })
                            ]}
                        >
                            <Input type="password" autoComplete="off"/>
                        </Form.Item>
                    </Form>
                </Modal>
                <Modal
            destroyOnClose
            title={<div className="title-Style">编辑子项目资源</div>}
            visible={childEditorVisible}
            onCancel={this.editorCancel}
            maskClosable={false}
            bodyStyle={{ backgroundColor: "#f0f3f6" }}
            footer={
              <div className="footer-Style">
                <Button
                  type="primary"
                  style={{ color: "white", borderRadius: 5 }}
                  onClick={this.editorChildOrg}
                >
                  保存
                </Button>
                <Button
                  style={{ color: "#007cdb", borderRadius: 5 }}
                  onClick={this.editorCancel}
                >
                  取消
                </Button>
              </div>
            }
          >
            <Form
              labelCol={{ span: 24 }}
              wrapperCol={{ span: 20 }}
              ref={this.editRef}
            >
            <Form.Item
                label={<span className="formItemStyle">负责人姓名</span>}
                rules={[{ required: true, message: "请输入负责人姓名" },]}
                initialValue={childRecord.name}
                name="chargePeoName"
                                >
             <Input autoComplete="off" />
             </Form.Item>
             <Form.Item
                     label={<span className="formItemStyle">负责人电话</span>}
                     initialValue={childRecord.phone}
                       rules={[
                        { required: true, message: "请输入负责人电话" },
                      { validator: validateTel },
                          ]}
                                    name="chargePeoTel"
                                >
                                    <Input autoComplete="off" />
                                </Form.Item>
               <Form.Item
                  label={<span className="formItemStyle">负责人邮箱</span>}
                  rules={[{ required: true, message: "请输入负责人邮箱" }, { validator: validateEmail }]}
                    name="chargePeoEmail"
                   >
                   <Input autoComplete="off" />
               </Form.Item>
            </Form>
          </Modal>
            </Content>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        organization: state.getIn(['organization', 'organization']).toJS(),
        subFlag:state.getIn(['organization','subFlag']),
        childDataSource:state.getIn(['organization','childDataSource']),
        parentRecord:state.getIn(['organization','parentRecord']),
        childPageNum:state.getIn(['organization','childPageNum'])
    }
}

const mapDispatchToProps = (dispatch) => ({
    // getConfig(userName){
    //   dispatch(actionCreators.getAllConfigOperation(userName));
    // },
    back(){
        dispatch({
            type:'back',
            flag:0
        })
    },
    getChildData(userId){
        dispatch(actionCreators.getChildData(userId))
    },
    deleteSub(userId){
        dispatch(actionCreators.deleteChildInfo(userId))
    },
    startChildEnable(userId,childUserId){
        dispatch(actionCreators.startChildEnable(userId,childUserId))
    },
    noChildEnable(userId,childUserId){
        dispatch(actionCreators.noChildEnable(userId,childUserId))
    },
    saveChildEdit(editValue,childUserId){
        dispatch(actionCreators.saveChildEdit(editValue,childUserId))
    },
    addChildOrg(addValue,childUserId){
        dispatch(actionCreators.addChildOrg(addValue,childUserId))
    },
    childResetPwd(pwdValue,childUserId){
        dispatch(actionCreators.childResetPwd(pwdValue,childUserId))
    }
})

export default connect(mapStateToProps, mapDispatchToProps)(subOrganization);